//
//  AriaController.swift
//  AriaNgUI
//
//  Created by 石正义 on 2017/9/8.
//  Copyright © 2017年 Shizhy. All rights reserved.
//
import Cocoa
import Foundation

class AriaController: NSObject {

    override func awakeFromNib() {
        print("hello world")
    }
    
    @IBOutlet weak var startAriaItem: NSMenuItem!
    @IBAction func startAria(_ sender: NSMenuItem) {
        let task:Process = Process()
        let pipe:Pipe = Pipe()
        
        task.launchPath = "/usr/local/aria2/bin/aria2c"
        task.arguments = ["-D"]
        task.standardOutput = pipe
        task.launch()
        
        let handle = pipe.fileHandleForReading
        let data = handle.readDataToEndOfFile()
        let result_s = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        if (result_s != nil) {
            print("Success")
            startAriaItem.title="已启动"
        } else {
            print("Fail")
        }
    }
    
    @IBAction func openAriaWeb(_ sender: NSMenuItem) {
        if let url = URL(string: "https://github.com/aria2/aria2/releases/"), NSWorkspace.shared().open(url) {
            print("default browser was successfully opened")
        }
    }
    @IBAction func restoreAria2Conf(_ sender: NSMenuItem) {
        let filePath = Bundle.main.resourcePath! + "/config/aria2.conf";
        let defaultContent = FileOperations.readFile(path: filePath)
        if defaultContent==nil {
            // 程序损坏
        } else {
            
            let result = FileOperations.writeFile(dirName: NSHomeDirectory() +  "/.aria2/", fileName: "aria2.conf", data: defaultContent!)
            if result {
                print("恢复默认")
            }
        }
    }
}
